import os
import cv2
from tqdm import tqdm
import tifffile as tifi

def get_corners(shape, crop_size, rate=0):  # 对于建库粗粒度搜索，重叠度可设为0
    overlap = int(crop_size * rate)

    result = []
    h, w, _ = shape
    y_coords = range(0, h, crop_size - overlap)
    x_coords = range(0, w, crop_size - overlap)
    for y in y_coords:
        for x in x_coords:
            # 确定子影像的结束位置
            x_end = x + crop_size
            y_end = y + crop_size
            # 裁剪子影像
            if(x + crop_size > w):
                x = w - crop_size
                x_end = w
            if(y + crop_size > h):
                y = h - crop_size
                y_end = h
            result.append([y, y_end, x, x_end])
    return result


if __name__ == '__main__':
    # 以不同尺寸从上一步处理后bing地图上裁剪影像，所有裁剪后图像均缩放至448*448
    # 假定上一步处理后bing图像的分辨率为1m，命名的第二位表示保存图像的分辨率，数值上为 裁剪尺寸/448
    root_path = r'G:\data\satgeoloc_finals_basemap\bing_process'
    save_path = r'G:\data\satgeoloc_finals_basemap\reference_image'
    # root_path = r'D:/Temp/bing_process'
    # save_path = r'D:/Temp/reference_image'
    os.makedirs(save_path, exist_ok=True)
    crop_size_list = [600, 1200, 2400, 4800, 9600]
    # crop_size_list = [2400, 4800]

    image_list = os.listdir(root_path)
    for image_name in tqdm(image_list):
        # img = cv2.imread(f'{root_path}/{image_name}', cv2.IMREAD_UNCHANGED)
        img = tifi.imread(f'{root_path}/{image_name}')[:, :, [2, 1, 0]]

        for size in crop_size_list:
            crop_list = get_corners(img.shape, size, 0.4)
            for item in crop_list:
                y, y_end, x, x_end = item
                croped_img = img[y:y_end, x:x_end]

                save_img = cv2.resize(croped_img, (448, 448))
                cv2.imwrite(f'{save_path}/{image_name[:-4]}_{round(size/448, 2)}_{x}_{y}_{x_end}_{y_end}.jpg', save_img)
            
